#!/usr/bin/env bash

# Copyright 2018, Rackspace US, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

# {{ ansible_managed }}

set -e

{{ nspawn_cache_prep_pre_commands }}

{% include 'templates/prep-scripts/_container_sys_setup.sh.j2' %}

# Update base distribution
export DEBIAN_FRONTEND=noninteractive

apt-get remove -y --purge snap* nspawn* lxd* resolvconf || true
apt-get update

apt-get install -y -o Dpkg::Options::="--force-confdef" -o Dpkg::Options::="--force-confold" --force-yes eatmydata
export LD_PRELOAD=/usr/lib/{{ ansible_architecture }}-linux-gnu/libeatmydata.so

apt-get install -y -o Dpkg::Options::="--force-confdef" -o Dpkg::Options::="--force-confold" --force-yes {{ nspawn_container_distro_required_packages | join(' ') }}
apt-get install -y -o Dpkg::Options::="--force-confdef" -o Dpkg::Options::="--force-confold" --force-yes {{ nspawn_container_distro_packages | join(' ') }}
apt-get upgrade -y -o Dpkg::Options::="--force-confdef" -o Dpkg::Options::="--force-confold" --force-yes
apt-get clean
rm /var/cache/apt/archives/lock || true

rm -f /usr/bin/python || true
ln -s /usr/bin/python2.7 /usr/bin/python

for action in disable; do
  systemctl ${action} resolvconf.service || true
  systemctl ${action} systemd-networkd-resolvconf-update.path || true
  systemctl ${action} systemd-networkd-resolvconf-update.service || true
  systemctl ${action} ssh.service || true
done

systemctl enable systemd-hostnamed.service
systemctl enable systemd-networkd.service
systemctl enable systemd-resolved.service
ln -sf /var/run/systemd/resolve/resolv.conf /etc/resolv.conf

userdel --force --remove ubuntu || true

{{ nspawn_cache_prep_post_commands }}
